from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from django.utils import simplejson as json
import urllib2
import re
import xmlrpclib
from google.appengine.ext import db
from google.appengine.api import users 
from lib import wpdb 

class Ajax1(webapp.RequestHandler):
  def post(self):
    wp_url_xmlrpc = self.request.get("wp_url_xmlrpc")
    response = ""
    self.response.headers['Content-Type'] = 'application/json'
    try:
      data = urllib2.urlopen(wp_url_xmlrpc).read()
      if re.search('XML-RPC',data,re.I):
        response = {'status':"ok",'message':"Valid processing to next step"}
      else:
        response = {'status':"notok",'message':"Don't seem to be a valid URL"}
    except urllib2.HTTPError, e:
      response = {'status':"error",'message':"no xml-rpc service found at "+wp_url_xmlrpc+" "+str(e.code)}
    except:
      response = {'status':"error",'message':"no xml-rpc service found at "+wp_url_xmlrpc}

    self.response.out.write(json.dumps(response))

  def get(self):
    self.response.headers['Content-Type'] = 'application/json'
    self.response.out.write(json.dumps({'message':"strange"}))

class Ajax2(webapp.RequestHandler):
  def post(self):
    wp_password = self.request.get("wp_password")
    wp_username = self.request.get("wp_username")
    wp_url_xmlrpc = self.request.get("wp_url_xmlrpc")
    proxy = xmlrpclib.ServerProxy(wp_url_xmlrpc)
    response = ""
    form = ""
    try:
      listOfBlogs = proxy.wp.getUsersBlogs(wp_username,wp_password)
      messages = []
      for blog in listOfBlogs:
        form += "<input type='checkbox' name='wp_blogs_id[]' value='"+blog['blogid']+"'></input>"+blog['blogName']+"<br/>"
        messages.append(blog['blogName'])
      response = {'status':"ok",'message':"found:"+(', '.join(messages)),'form':form}
    except Exception, e:
      response = {'status':"error",'message':"error unable to get blogs for user: "+e.message}
    self.response.headers['Content-Type'] = 'application/json'
    self.response.out.write(json.dumps(response))

class Ajax3(webapp.RequestHandler):
  def post(self):
    wp_password = self.request.get("wp_password")
    wp_username = self.request.get("wp_username")
    wp_url_xmlrpc = self.request.get("wp_url_xmlrpc")
    proxy = xmlrpclib.ServerProxy(wp_url_xmlrpc)
    response = ""
    try:
      listOfBlogs = proxy.wp.getUsersBlogs(wp_username,wp_password)
      listOfBlogIdSelected = self.request.get_all("wp_blogs_id[]")
      countBlog=0
      for blog in listOfBlogs:
        if blog['blogid'] in listOfBlogIdSelected:
          if wpdb.WordpressBlog.all().filter('xmlrpc =',blog['xmlrpc']).filter('blogid =',blog['blogid']).filter("username =",wp_username).count() >0:
          # update
            wp = wpdb.WordpressBlog.all().filter('xmlrpc =',blog['xmlrpc']).filter('blogid =',blog['blogid']).filter('username =',wp_username).get()
            wp.blogName=blog['blogName']
            wp.username=wp_username
            wp.password=wp_password
            wp.put()
            countBlog+=1
          else:
              # insert
            wp = wpdb.WordpressBlog(
              url=blog['url'],
              blogid=blog['blogid'],
              xmlrpc=blog['xmlrpc'],
              blogName=blog['blogName'],
              username=wp_username,
              password=wp_password,
              owner = users.get_current_user()
            )
            wp.put()
            countBlog+=1
      if countBlog > 0:      
        response = {'status':"ok",'message':"Great ! "+str(countBlog)+" successfully registered "}
      else:
        response = {'status':"error",'message':"No item selected: "+(', '.join(listOfBlogIdSelected))}
    except Exception ,e:
      response = {'status':"error",'message':"error unable to register blogs for user: "+e.message}
    self.response.headers['Content-Type'] = 'application/json'
    self.response.out.write(json.dumps(response))

application = webapp.WSGIApplication(
	[('/register/ajax/step1', Ajax1),
	('/register/ajax/step2', Ajax2),
	('/register/ajax/step3', Ajax3)],
	debug=True)

def main():
  run_wsgi_app(application)

if __name__ == "__main__":
  main()
